package org.ruanjj.threesumclosest;

import java.util.Arrays;

public class Solution1 {
    public int threeSumClosest(int[] nums, int target){
        Arrays.sort(nums);
        int res = nums[0] + nums[1]+nums[2];
        for(int i = 0; i < nums.length-2; i++){
            int left = i+1;
            int right = nums.length-1;
            while(left < right){
                int sum = nums[i]+nums[left]+nums[right];
                if(sum == target){
                    return target;
                }
                if(Math.abs(sum-target) < Math.abs(res-target)){
                    res = sum;
                }
                if(sum > target){
                    right--;
                }else{
                    left ++;
                }
            }
        }
        return res;
    }
}
